package org.vectrics.batch;

import java.util.HashMap;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;

/**
 * @author MMoore
 */
public class BatchManager {
	public static final String BATCH_ID_SURROGATE_KEY = "batch.id";
	private static BatchManager instance = null;
	private HashMap<Long, Batch> runningBatches = new HashMap<Long, Batch>();
	private transient Logger log = Logger.getLogger(BatchManager.class);
	
	public static BatchManager getInstance() {
		if (instance == null)
			instance = new BatchManager();
		return(instance);
	}
	
	/**
	 * 
	 */
	private BatchManager() {
		super();
	}
	
	public synchronized Long getNextBatchId() {
		ThreadProperties.getSession().clear();
		Long nextId = CoreServiceLocator.getSurrogateKeyService().getKey(BATCH_ID_SURROGATE_KEY);
		//if (nextId.longValue() <= lastId.longValue()) {
		//	throw new SystemException("SurrogateKey is less than previous issued value.  Current id = " 
		//			+ nextId + "  last id =" + lastId);
		//	//nextId = new Long(lastId.longValue() + 1);
		//}
		if (nextId == null)
			throw new SystemException("Surrogate service returned null key for: " + BATCH_ID_SURROGATE_KEY);
		
		if (log.isDebugEnabled())
			log.debug("Next batch id = " + nextId);
		return(nextId);
	}

	public Batch findRunningBatch(Long id) {
		Batch batch = (Batch)runningBatches.get(id);
		return(batch);
	}
	
	protected void registerBatchStarted(Batch batch) {
		runningBatches.put(batch.getId(), batch);
	}

	protected void registerBatchEnded(Batch batch) {
		runningBatches.remove(batch.getId());
	}
}
